<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDiglog  =true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="rolesList" vorder stripe>
        <!--展开列  -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格系统布局 -->
            <!-- 动态绑定底边框 -->
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',i1 === 0 ? 'bdtop':'' ,'vcenter'] "
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <!-- 索引i2 -->
                <el-row
                  :class="[i2 ===0 ?'':'bdtop' ,'vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 通过for循环渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre> {{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditRoles(scope.row.id)"
            >编辑</el-button>

            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRoles(scope.row.id)">删除</el-button>

            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRightsDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRIghtsdialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treetProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRIghtsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDiglog" width="50%" @close="addRolesColsed">
      <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="80px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDiglog = false">取 消</el-button>
        <el-button type="primary" @click="addRolesbtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editRolesDiglog" width="50%" @close="editRolesClosed">
      <el-form :model="editRolesForm" :rules="editRolesRules" ref="editRolesRef" label-width="80px">
        <el-form-item label="角色名" prop="roleName" >
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDiglog = false">取 消</el-button>
        <el-button type="primary" @click="editRolesBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolesList: [],
      //展示分配权限的对话框
      setRIghtsdialogVisible: false,
      //所有权限数据
      rightsList: [],
      //树形控件的属性绑定对象
      treetProps: {
        //显示的名字
        label: "authName",
        //下边的子节点
        children: "children",
      },
      //默认选中的节点id数组值
      defKeys: [],
      //当前即将分配权限的id
      roleId: "",
      //添加角色的对话框状态
      addRolesDiglog: false,
      //添加角色的表单数据
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      //验证添加角色表单的规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      //修改角色对象对话框的事件
      editRolesDiglog: false,
      //修改通过id查询角色的对象
      editRolesForm: "",
      //修改角色的验证规则
      editRolesRules: {
         roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200) {
        this.$message.error("获取角色失败")
      }
      this.rolesList = res.data

      console.log(this.rolesList)
    },
    //根据id删除对应的权限
    async removeRightById(role, rightId) {
      //弹框提示是否删除

      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err)

      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除")
      }

      //console.log('确认了删除');
      //删除请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        this.$message.error("删除权限失败")
      }
      // this.getRolesList()
      //因为再次调用方法会重新拉去一下页面  所以不建议使用
      //将最新数据data重新付一下值
      role.children = res.data
    },
    //展示分配权限的对话框
    async setRightsDialog(role) {
      this.roleId = role.id
      //获取到所有权限的数据
      const { data: res } = await this.$http.get("rights/tree")
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败")
      }
      //把获取到的权限数据保存到data中
      this.rightsList = res.data
      console.log(this.rightsList)
      //递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRIghtsdialogVisible = true
    },
    //通过递归的形式获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      //node  节点  arr  数组
      if (!node.children) {
        //if当前node节点不包含children属性则是三级节点
        return arr.push(node.id)
      }

      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    //监听分配权限对话框关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    //分配权限所有的id值
    async allotRights() {
      //先拿到所有的key
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idStr = keys.join(",")

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败")
      }
      this.$message.success("分配权限成功")
      this.getRolesList()
      this.setRIghtsdialogVisible = false
    },
    //角色添加确定按钮
    addRolesbtn() {
      //对整个表单进行一个与验证
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("您所填写的字段有误")
        }
        //为true走一个添加请求
        const { data: res } = await this.$http.post("roles", this.addRolesForm)
        if (res.meta.status !== 200) {
          this.$message.error("添加失败")
        }
        this.$message.success("添加成功")
        this.addRolesDiglog = false
        this.getRolesList()
      })
    },
    //添加角色对话框的关闭事件
    addRolesColsed() {
      //关闭之后对表单进行一个重置
      this.$refs.addRolesRef.resetFields()
    },
    //点击编辑按钮
    async showEditRoles(id) {
      //通过id去查询当前角色的信息
      const { data: res } = await this.$http.get("roles/" + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败')
      }
      //成功后吧查询到的对象赋给editRolesFrom
      this.editRolesForm=res.data
      this.editRolesDiglog=true
    },
    //监听编辑对话框取消
    editRolesClosed(){
      //对表单重置
      this.$refs.editRolesRef.resetFields()
    },
    //监听编辑角色确定按钮
    editRolesBtn(){
      //对表单进行预验证
      this.$refs.editRolesRef.validate(async valid=>{
        if(!valid){
          return   this.$message.error('修改数据有误')
        }
        //走一个修改请求
      const {data:res}=await  this.$http.put('roles/'+ this.editRolesForm.roleId,
        {roleName:this.editRolesForm.roleName,roleDesc: this.editRolesForm.roleDesc})
        if(res.meta.status!==200){
          return this.$message.error('修改失败')
        }
        //更新成功
        this.editRolesDiglog=false
        this.getRolesList()
        this.$message.success('修改成功')
      })
    },
    //监听删除按钮
    async delRoles(id){
      //进行一个弹框设置
      const res=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(res!=="confirm"){
          return this.$message.info('取消了删除')
        }
        //确定删除
       const {data:res1}=await this.$http.delete('roles/'+id)
       if(res1.meta.status!==200){
         return this.$message.error("删除失败")
       }
       this.getRolesList()
       this.$message.success('删除成功')
    }
  },
}
</script>
<style lang="less">
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>